package elijah.eupdater.ctr;


import ch.qos.logback.core.util.FileUtil;
import elijah.eupdater.bean.ListResult;
import elijah.eupdater.bean.Result;
import elijah.eupdater.dao.TerminalDeviceMapper;
import elijah.eupdater.entity.TerminalDevice;
import elijah.eupdater.entity.UserInfo;
import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@RestController("eupdater_web")
@RequestMapping("eupdater/web")
@CrossOrigin
public class WebCtr {
    @Autowired
    private TerminalDeviceMapper terminalDeviceMapper;


    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo) {
        // 在这里编写验证逻辑
        if ("admin".equals(userInfo.getUsername()) && "admin".equals(userInfo.getPassword())) {
            // 登录成功，可以进行相应的操作
            return new Result();
        }
        // 登录失败，返回登录页面并显示错误信息
        return new Result(-1, "密码错误");

    }

    @GetMapping("getTerminalDevices")
    public ListResult getTerminalDevices(TerminalDevice terminalDevice, Integer current, Integer pageSize) {
        List<TerminalDevice> terminalDevices = terminalDeviceMapper.selectAll(terminalDevice, current, pageSize);
        return new ListResult(terminalDevices).setTotal(terminalDeviceMapper.selectAll(terminalDevice, null, null).size());
    }

    @PostMapping("updateTerminalDevice")
    public Result getTerminalDevice(@RequestBody TerminalDevice terminalDevice) {
        int ret = terminalDeviceMapper.updateByPrimaryKeySelective(terminalDevice);
        return new Result();
    }

    @GetMapping("deleteTerminalDevice")
    public Result deleteTerminalDevice(String deviceId, String packageName) {
        int ret = terminalDeviceMapper.deleteByPrimaryKey(deviceId, packageName);
        return new Result<>();
    }

    @PostMapping("deleteTerminalDevices")
    public Result deleteTerminalDevices(@RequestBody List<TerminalDevice> terminalDevices) {
        for (TerminalDevice terminalDevice : terminalDevices) {
            int ret = terminalDeviceMapper.deleteByPrimaryKey(terminalDevice.getDeviceId(), terminalDevice.getPackageName());

        }
        return new Result<>();
    }

    @PostMapping("uploadApk")
    public Result uploadApk(@RequestPart(value = "files") MultipartFile apk) throws IOException {

        File dir = new File(getFilePath());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, apk.getOriginalFilename());
        if (file.exists()) {
            FileUtils.forceDelete(file);
        }

        apk.transferTo(file);

        ApkFile apkFile = null;
        try {
            apkFile = new ApkFile(file);
            ApkMeta apkMeta = apkFile.getApkMeta();

            TerminalDevice terminalDevice = new TerminalDevice();
            terminalDevice.setPackageName(apkMeta.getPackageName());
            terminalDevice.setUpdateVersionCode(apkMeta.getVersionCode());
            terminalDevice.setUpdateVersionName(apkMeta.getVersionName());
            terminalDevice.setUpdateFileName(file.getName());
            terminalDevice.setUpdateFilePath("update/" + file.getName());
            return new Result(terminalDevice);

        } catch (IOException e) {
            e.printStackTrace();
            file.delete();
            throw new IllegalArgumentException("更新包解析失败：", e);
        } finally {
            if (apkFile != null) {
                apkFile.close();

            }

        }


    }


    @PostMapping("updateAppByPackageName")
    public Result updateAppByPackageName(@RequestBody TerminalDevice terminalDevice) {
        int ret = terminalDeviceMapper.updateTerminalDeviceApp(terminalDevice);
        return new Result<>();
    }

    @GetMapping("getUnregisteredDevices")
    public ListResult getUnregisteredDevices() {
        List<TerminalDevice> terminalDevices = terminalDeviceMapper.getUnregisteredDevices();
        return new ListResult(terminalDevices);
    }

    @PostMapping("registeredDevices")
    public Result getUnregisteredDevices(@RequestBody List<TerminalDevice> terminalDevices) {
        for (TerminalDevice terminalDevice : terminalDevices) {
            int ret = terminalDeviceMapper.registeredDevice(terminalDevice);
        }
        return new Result();
    }

    public String getFilePath() {
        return Paths.get(Paths.get("webapps/update").toAbsolutePath().toString()).normalize().toFile().getPath();
    }
}
